package pers.sloera.interview.bytedance;

/**
 * 字符串相乘
 * class pers.sloera.interview.bytedance
 * user sloera
 * date 2022/3/24
 */
public class Solution {
    // 会超过int和long
    // 1 * 100 + 2 * 10 + 3 * 1
    // 4 * 100 + 5 * 10 + 6 * 1
    public static void main(String[] args) {
        String a = "123";
        String b = "456";
        // 进位
        // 0 123456
        int[] result = new int[a.length() + b.length()];
        for (int i = a.length() - 1; i >= 0; i--) {
            for (int j = b.length() - 1; j >= 0; j--) {
                final char left = a.charAt(i);
                final char right = b.charAt(j);
                final int i1 = Integer.parseInt(left + "") * Integer.parseInt(right + "");
                handleCarry(result, i + j + 1, i1);
            }
            handleCarry(result, i, 0);
        }
        final StringBuilder stringBuilder = new StringBuilder();
        int zeroIndex = 0;
        while (result[zeroIndex++] == 0) {
        }
        for (int i = zeroIndex - 1; i < result.length; i++) {
            stringBuilder.append(result[i]);
        }
        System.out.println(stringBuilder);
    }

    /**
     * 处理进位
     *
     * @return void
     * @date 2022/3/24
     */
    private static void handleCarry(int[] result, int index, int num) {
        for (int i = index; i >= 0; i--) {
            int temp = result[index] + num;
            if (temp >= 10) {
                result[index] = temp % 10;
                num = temp / 10;
                index--;
            } else {
                result[index] = temp;
                return;
            }
        }
    }

}
